package com.etongwl.socketlibrary.library2;


/**
 * Created by jason on 16/6/27.
 */
public class HanderCore {
    //消息队列
    MessageQueueCore<MessageCore> mQueue;
    //循环
    LooperCore mLooper;

    public HanderCore() {
        mLooper = LooperCore.myLooper();
        if (mLooper == null) {
            mLooper = LooperCore.getLooper();
            if (mLooper ==null){
                throw new RuntimeException(
                    "Can't create handler inside thread that has not called Looper.prepare()");
            }
        }
        mQueue = mLooper.mQueue;
    }

    public final  synchronized MessageCore obtainMessage() {
        return MessageCore.obtain(this);
    }


    public void dispatchMessage(MessageCore msg) {
        handleMessage(msg);
    }

    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(MessageCore msg) {//
        if (msg.what == -1) {//退出
            quit();
        }
    }

    /**
     * 添加消息到消息队列
     *
     * @param msg
     */
    public void sendMessage(MessageCore msg) {
        synchronized (this) {
            System.out.println("sendMessage is run! ");
            try {
                mQueue.setMessage(msg);
                System.out.println("sendMessage is run mQueue hashCode = "+mQueue.hashCode()+",num="+mQueue.getNum());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 退出
     */
    private void quit() {
        if (mLooper != null) {
            mLooper.quit();
        }
    }
}
